package com.lineage.server.timecontroller.npc;

import com.lineage.server.model.Instance.L1NpcInstance;
import com.lineage.server.thread.GeneralThreadPool;
import com.lineage.server.world.WorldNpc;
import java.util.Collection;
import java.util.Iterator;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class NpcRestTimer extends TimerTask {
  private static final Log _log = LogFactory.getLog(NpcRestTimer.class);
  
  private ScheduledFuture<?> _timer;
  
  public void start() {
    int timeMillis = 5000;
    this._timer = GeneralThreadPool.get().scheduleAtFixedRate(this, 5000L, 5000L);
  }
  
  public void run() {
    try {
      Collection<L1NpcInstance> allMob = WorldNpc.get().all();
      if (allMob.isEmpty())
        return; 
      Iterator<L1NpcInstance> iter = allMob.iterator();
      while (iter.hasNext()) {
        L1NpcInstance npc = iter.next();
        if (npc == null)
          continue; 
        if (npc.get_stop_time() < 0)
          continue; 
        int time = npc.get_stop_time();
        npc.set_stop_time(time - 5);
        if (npc.get_stop_time() <= 0) {
          npc.set_stop_time(-1);
          npc.setRest(false);
        } 
        Thread.sleep(50L);
      } 
    } catch (Exception e) {
      _log.error("NPC动作暂停时间轴异常重启", e);
      GeneralThreadPool.get().cancel(this._timer, false);
      NpcRestTimer restTimer = new NpcRestTimer();
      restTimer.start();
    } 
  }
}
